from uhf_rfid_reader import UHFReader
import time

def handle_tags(tags):
    """Callback function to handle discovered tags."""
    print(f"\nFound {len(tags)} tags:")
    for tag in tags:
        print(f"  - EPC: {tag.epc}")
        print(f"    Antenna: {tag.antenna_id}")
        print(f"    RSSI: {tag.rssi}dBm")
        print(f"    Time: {tag.timestamp}")

def main():
    # Create reader instance
    reader = UHFReader()
    
    try:
        # Connect to the reader using serial port
        conn_str = "RDType=UHF;CommType=COM;COMName=/dev/ttyUSB0;BaudRate=38400"
        print(f"Connecting to reader using: {conn_str}")
        if not reader.open(conn_str):
            print("Failed to connect to reader")
            return
            
        print("Successfully connected to reader")
        
        # Get and display reader information
        reader_info = reader.get_reader_info()
        if reader_info:
            print("\nReader Information:")
            print("-" * 50)
            print(reader_info)
            print("-" * 50)
        else:
            print("Failed to get reader information")
        
        # Start inventory with callback
        print("\nStarting inventory operation...")
        reader.set_inventory_callback(handle_tags)
        
        if reader.start_inventory():
            print("Scanning for tags for 10 seconds...")
            time.sleep(10)
            
            reader.stop_inventory()
            print("\nStopped inventory operation")
            
            # Example tag operations
            print("\nDemonstrating tag read/write operations...")
            print("Note: These operations require a tag to be present")
            
            # Replace with an actual tag EPC found during inventory
            example_epc = "E28011700000020B86F11111"  
            
            # Read TID memory bank
            print("\nReading TID bank...")
            tid_data = reader.read_tag_data(example_epc, mem_bank=2, start_word=0, word_count=6)
            if tid_data:
                print(f"TID: {tid_data.hex()}")
            else:
                print("Failed to read TID")
            
            # Read user memory bank
            print("\nReading User memory bank...")
            user_data = reader.read_tag_data(example_epc, mem_bank=3, start_word=0, word_count=4)
            if user_data:
                print(f"User Data: {user_data.hex()}")
            else:
                print("Failed to read user data")
            
            # Write to user memory
            print("\nWriting to User memory bank...")
            write_data = bytes.fromhex('1234567890AB')  # 6 bytes = 3 words
            if reader.write_tag_data(example_epc, mem_bank=3, start_word=0, data=write_data):
                print("Successfully wrote data")
            else:
                print("Failed to write data")
            
            # Verify written data
            print("\nVerifying written data...")
            verify_data = reader.read_tag_data(example_epc, mem_bank=3, start_word=0, word_count=3)
            if verify_data:
                print(f"Read back data: {verify_data.hex()}")
                if verify_data == write_data:
                    print("Write verification successful!")
                else:
                    print("Write verification failed!")
            else:
                print("Failed to read back data")
            
    except Exception as e:
        print(f"Error: {e}")
    finally:
        # Always close the connection
        reader.close()
        print("\nConnection closed")

if __name__ == "__main__":
    main()